import sys
import os
import tempfile
import moviepy.config as mpconf
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtCore import QUrl, Qt

from bridge.bridge import Bridge
from utils.tools import resource_path


moviepy_temp_dir = os.path.join(tempfile.gettempdir(), "moviepy_temp")
os.makedirs(moviepy_temp_dir, exist_ok=True)
mpconf.change_settings({
    "IMAGEMAGICK_BINARY": resource_path(r"libs/ImageMagick-7.1.1-Q16-HDRI/magick.exe"),
    "TEMP_DIR": moviepy_temp_dir,
})
os.environ["FFMPEG_GPU_ACCELERATION"] = "1"  # 开启 GPU 加速


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("AiMix")

        # 获取主屏幕的可用区域几何信息（考虑任务栏等系统区域）
        available_geometry = QApplication.primaryScreen().availableGeometry()
        screen_width = available_geometry.width()
        screen_height = available_geometry.height()

        self.setFixedSize(2500, 1600)
        # 创建 WebEngineView 加载 HTML
        self.web_view = QWebEngineView(self)
        self.setCentralWidget(self.web_view)

        # 创建 WebChannel 连接前端与后端
        self.channel = QWebChannel()
        self.bridge = Bridge()  # 逻辑桥接对象
        # 注册桥接对象
        self.channel.registerObject("Bridge", self.bridge)  # 逻辑桥接对象

        self.web_view.page().setWebChannel(self.channel)
        html_path = resource_path(r"view/index.html")
        self.web_view.load(QUrl.fromLocalFile(os.path.abspath(html_path)))

        # 将窗口移动到屏幕左上角（0, 0）
        self.move(0, 0)

        # 确保窗口不会被最大化按钮最大化
        self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
